import requestInterceptor from '../utils/requestInterceptor'; // 导入请求拦截器实例
import { toast } from '../utils/extendApi';
// 导入本地存储 api
import { setStorage, clearStorage } from '../utils/storage'

/**
 * @description 生成Token
 */
export const generateToken = () => {
  const md5 = require('js-md5');
  const appId = 61;
  const appKey = '2fb6c758-d2d2-45fd-ae31-08ee0cfbf0ac';
  const timestamp = Date.now();
  let param = `ApiRequest{appId=${appId},appKey=${appKey},timeStamp=${timestamp}}`;
  let tokenStr = md5(param);
  // 将token和timestamp存储到本地
  setStorage('token', tokenStr)
  setStorage('timeStamp', timestamp)
}

/**
 * @description 进行登录操作
 * @param {string} username - 用户名
 * @param {string} password - 密码
 * @returns Promise
 */
export const reqLogin = (userName, password, callback) => {
  requestInterceptor({
    url: '/app/user/api/login',
    method: 'POST',
    data: { userName, password }
  }).then((res) => {
    console.log('登录成功，返回数据:', res.data);
    callback(res.data)
  }).catch((err) => {

    // 根据错误类型进行提示
    console.log("登录页面提示:", err.message);
    if (err.message === '请求出现错误：登录失败') {
      toast({
        title: "用户名不存在或密码错误！",
        icon: 'none'
      });
    } else {
      toast({
        title: err.message,
        icon: 'none'
      });
    }
    // 清除临时token
    clearStorage();
    callback(null)
  });
};

/**
 * @description 获取用户信息
 * @returns Promise
 */
export const reqUserInfo = (userId, callback) => {
  generateToken(); // 生成用于请求的token

  requestInterceptor({
    url: '/app/user/api/getById',
    method: 'GET',
    data: { userId }
  }).then((res) => {
    if (res.data.data == null) {
      toast({
        title: "该用户信息不存在",
        icon: 'none'
      });
      callback(null)
      return;
    }
    console.log('获取用户信息成功，返回数据:', res.data);
    callback(res.data)
  }).catch((err) => {
    // 根据错误类型进行提示
    console.log("设置页面提示:", err.message);
    toast({
      title: "获取用户信息错误！",
      icon: 'none'
    });
    callback(null)
  });
}

// 更新用户信息
export const updateUserInfo = (userId, userName, classesId, nickName, email, phonenumber, sex, status, updateBy) => {
  requestInterceptor({
    url: '/app/user/api/edit',
    method: 'POST',
    data: { userId, userName, classesId, nickName, email, phonenumber, sex, status, updateBy }
  }).then((res) => {
    console.log('个人信息修改成功，返回数据:', res.data);
    toast({
      title: '修改成功',
      icon: 'none'
  });
  }).catch((err) => {
    console.log(err.message);
    toast({
      title: "修改失败: " + err.message,
      icon: 'none',
    });
  });
};
